/*
 * Copyright 2010 Assert Developments
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package be.ad.coffeebreak.web;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * A servlet context listener that sets up a guice injector that's shared by our web application.  This guice injector
 * will be added to the servlet context under the WebConstants.ATTRIBUTE_INJECTOR key.
 *
 * @author Stefan Bangels
 */
public class GuiceServletContextListener implements ServletContextListener {

    /**
     * Initializes the context.
     *
     * @param servletContextEvent the servlet context event
     */
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.setAttribute(WebConstants.ATTRIBUTE_INJECTOR, createInjector());
    }

    /**
     * Create a guice injector for our web application.
     *
     * @return the guice injector
     */
    private Injector createInjector() {
        return Guice.createInjector(getModules());
    }

    /**
     * Get the guice modules for our web application.
     *
     * @return the guice modules
     */
    protected Module[] getModules() {
        return new Module[]{new WebModule()};
    }

    /**
     * Destroying the context.
     *
     * @param servletContextEvent the servlet context event
     */
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
        servletContext.removeAttribute(WebConstants.ATTRIBUTE_INJECTOR);
    }

}